package com.canyou.utils;

import com.canyou.constants.CommonConstants;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;

import java.util.Base64;

/**
 * OAuth2帮助类
 *
 * @author cgz
 * @date 2019/1/27
 */
public final class Oauth2Utils {

    private Oauth2Utils() {
    }

    /**
     * 根据header中的token获取用户ID
     *
     * @return 用户ID
     */
    public static Long getUserId() {
        String token = getToken();
        if (StringUtils.isBlank(token)) {
            return null;
        }
        return getUserId(token);
    }

    /**
     * 根据header中的token获取用户ID
     *
     * @return 用户ID
     */
    public static Long getUserId(String token) {
        String key = Base64.getEncoder().encodeToString(CommonConstants.SIGN_KEY.getBytes());
        Claims claims = Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody();
        return Long.valueOf(claims.get(CommonConstants.USER_ID).toString());
    }

    /**
     * 通过token获取用户名
     *
     * @param token
     * @return
     */
    public static String getUserName(String token) {
        String key = Base64.getEncoder().encodeToString(CommonConstants.SIGN_KEY.getBytes());
        Claims claims = Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody();
        return claims.get(CommonConstants.USER_NAME).toString();
    }

    /**
     * 获取请求中token
     *
     * @return token
     */
    public static String getToken() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null && auth instanceof OAuth2Authentication) {
            OAuth2AuthenticationDetails oAuth2AuthenticationDetails = (OAuth2AuthenticationDetails) auth.getDetails();
            return oAuth2AuthenticationDetails.getTokenValue();
        }
        return null;
    }

    /**
     * 获取当前登录用户名
     *
     * @return
     */
    public static String getUserName() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth == null) {
            return null;
        }
        Object principal = auth.getPrincipal();
        if (principal instanceof UserDetails) {
            return ((UserDetails) principal).getUsername();
        } else {
            return principal.toString();
        }
    }

    /**
     * 获取客户端ID
     *
     * @return
     */
    public static String getClientId() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth instanceof OAuth2Authentication) {
            return ((OAuth2Authentication) auth).getOAuth2Request().getClientId();
        }
        return null;
    }
}
